{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d65b7766",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "任务开始\n",
      "任务被取消（超时退出)\n",
      "超时了！\n"
     ]
    }
   ],
   "source": [
    "import asyncio\n",
    "\n",
    "async def slow_task():\n",
    "    try:\n",
    "        print(\"任务开始\")\n",
    "        await asyncio.sleep(5)\n",
    "        print(\"任务完成\")\n",
    "    except asyncio.CancelledError:\n",
    "        print(\"任务被取消（超时退出)\")\n",
    "        # 可以此处清理资源\n",
    "        raise  # 继续抛出给wait_for()处理\n",
    "\n",
    "async def main():\n",
    "    try:\n",
    "        await asyncio.wait_for(slow_task(), timeout=2)\n",
    "    except asyncio.TimeoutError:\n",
    "        print(\"超时了！\")\n",
    "\n",
    "await main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "a8e09231",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "任务1 开始执行\n",
      "任务1 执行完成\n",
      "收到结果: 任务1 的结果\n"
     ]
    }
   ],
   "source": [
    "import asyncio\n",
    "import time\n",
    "from concurrent.futures import ThreadPoolExecutor\n",
    "\n",
    "# 这是一个同步阻塞函数（模拟第三方库）\n",
    "def blocking_function(name, seconds):\n",
    "    print(f\"{name} 开始执行\")\n",
    "    time.sleep(seconds)  # 模拟耗时操作\n",
    "    print(f\"{name} 执行完成\")\n",
    "    return f\"{name} 的结果\"\n",
    "\n",
    "async def main():\n",
    "    # 创建线程池\n",
    "    with ThreadPoolExecutor(max_workers=3) as executor:\n",
    "        loop = asyncio.get_event_loop()\n",
    "        \n",
    "        # 在线程池中运行同步函数\n",
    "        result = await loop.run_in_executor(\n",
    "            executor, \n",
    "            blocking_function, \n",
    "            \"任务1\", 2\n",
    "        )\n",
    "        print(f\"收到结果: {result}\")\n",
    "\n",
    "# 在 Jupyter 中运行\n",
    "await main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "98273c84",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "开始计算 100\n",
      "开始计算 200\n",
      "开始计算 300\n",
      "计算 100 完成\n",
      "计算 200 完成\n",
      "计算 300 完成\n",
      "所有结果: [4999999950000000, 19999999900000000, 44999999850000000]\n"
     ]
    }
   ],
   "source": [
    "import asyncio\n",
    "import time\n",
    "from concurrent.futures import ThreadPoolExecutor\n",
    "\n",
    "def cpu_intensive_task(n):\n",
    "    \"\"\"模拟CPU密集型任务\"\"\"\n",
    "    print(f\"开始计算 {n}\")\n",
    "    total = 0\n",
    "    for i in range(n * 1000000):\n",
    "        total += i\n",
    "    print(f\"计算 {n} 完成\")\n",
    "    return total\n",
    "\n",
    "async def main():\n",
    "    with ThreadPoolExecutor(max_workers=3) as executor:\n",
    "        loop = asyncio.get_event_loop()\n",
    "        \n",
    "        # 并发运行多个CPU密集型任务\n",
    "        tasks = [\n",
    "            loop.run_in_executor(executor, cpu_intensive_task, 100),\n",
    "            loop.run_in_executor(executor, cpu_intensive_task, 200),\n",
    "            loop.run_in_executor(executor, cpu_intensive_task, 300)\n",
    "        ]\n",
    "        \n",
    "        # 等待所有任务完成\n",
    "        results = await asyncio.gather(*tasks)\n",
    "        print(f\"所有结果: {results}\")\n",
    "\n",
    "await main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "24f45091",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "任务 0 成功: 成功完成\n",
      "任务 1 失败: 任务失败了！\n",
      "任务 2 成功: 成功完成\n"
     ]
    }
   ],
   "source": [
    "import asyncio\n",
    "import time\n",
    "from concurrent.futures import ThreadPoolExecutor\n",
    "\n",
    "def risky_function(will_fail=False):\n",
    "    time.sleep(1)\n",
    "    if will_fail:\n",
    "        raise ValueError(\"任务失败了！\")\n",
    "    return \"成功完成\"\n",
    "\n",
    "async def main():\n",
    "    with ThreadPoolExecutor(max_workers=2) as executor:\n",
    "        loop = asyncio.get_event_loop()\n",
    "        \n",
    "        try:\n",
    "            # 创建多个任务，其中一个会失败\n",
    "            tasks = [\n",
    "                loop.run_in_executor(executor, risky_function, False),\n",
    "                loop.run_in_executor(executor, risky_function, True),\n",
    "                loop.run_in_executor(executor, risky_function, False)\n",
    "            ]\n",
    "            \n",
    "            results = await asyncio.gather(*tasks, return_exceptions=True)\n",
    "            \n",
    "            # 处理结果\n",
    "            for i, result in enumerate(results):\n",
    "                if isinstance(result, Exception):\n",
    "                    print(f\"任务 {i} 失败: {result}\")\n",
    "                else:\n",
    "                    print(f\"任务 {i} 成功: {result}\")\n",
    "                    \n",
    "        except Exception as e:\n",
    "            print(f\"发生错误: {e}\")\n",
    "\n",
    "await main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "a86c2845",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "任务已安排\n",
      "主程序继续执行\n",
      "任务开始\n",
      "任务结束\n"
     ]
    }
   ],
   "source": [
    "import asyncio\n",
    "import time\n",
    "\n",
    "async def my_task():\n",
    "    print(\"任务开始\")\n",
    "    await asyncio.sleep(1)\n",
    "    print(\"任务结束\")\n",
    "\n",
    "async def main():\n",
    "    task = asyncio.create_task(my_task())\n",
    "    print(\"任务已安排\")\n",
    "    time.sleep(4)\n",
    "    print(\"主程序继续执行\")\n",
    "    await task  # 等待任务执行完\n",
    "\n",
    "await main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "734ad3f1",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:__main__:[personal-server-2] | This is an example log message.\n"
     ]
    }
   ],
   "source": [
    "import logging\n",
    "from colorama import init, Fore, Style\n",
    "\n",
    "init(autoreset=True)\n",
    "\n",
    "# 配置日志记录器\n",
    "logger = logging.getLogger(__name__)\n",
    "logging.basicConfig(level=logging.INFO)\n",
    "\n",
    "def example_callback(host_name):\n",
    "    display_line = \"This is an example log message.\"\n",
    "    colors = [Fore.BLUE, Fore.GREEN, Fore.YELLOW, Fore.MAGENTA, Fore.CYAN]\n",
    "    color_index = hash(host_name) % len(colors)\n",
    "    color = colors[color_index]\n",
    "    logger.info(f\"{color}[{host_name}]{Style.RESET_ALL} | {display_line}\")\n",
    "\n",
    "# 测试调用\n",
    "example_callback(\"personal-server-2\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "4254168d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=== 命令输出 ===\n",
      "total 20\n",
      "drwxr-xr-x  5 root      root      4096 Mar  4 19:52 .\n",
      "drwxr-xr-x 24 root      root      4096 Aug  2 15:46 ..\n",
      "drwxr-xr-x 16 cc        cc        4096 Jan  1  2025 cc\n",
      "drwxr-xr-x 42 cc_ubuntu cc_ubuntu 4096 Jul 29 01:22 cc_ubuntu\n",
      "drwxr-xr-x  3 root      root      4096 Mar  4 19:52 pc\n",
      "命令退出状态: 1\n"
     ]
    }
   ],
   "source": [
    "import paramiko\n",
    "import time\n",
    "\n",
    "# 建立 SSH 连接\n",
    "ssh = paramiko.SSHClient()\n",
    "ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n",
    "ssh.connect('172.24.114.244', username='cc_ubuntu', password='789235')\n",
    "\n",
    "# 执行命令\n",
    "stdin, stdout, stderr = ssh.exec_command('ls -la /home')\n",
    "\n",
    "# 示例1: 读取正常输出\n",
    "print(\"=== 命令输出 ===\")\n",
    "for line in stdout:\n",
    "    print(line.strip())\n",
    "\n",
    "# 示例2: 检查错误信息\n",
    "error_output = stderr.read().decode()\n",
    "if error_output:\n",
    "    print(\"=== 错误信息 ===\")\n",
    "    print(error_output)\n",
    "\n",
    "\n",
    "\n",
    "# 示例4: 处理需要交互的命令\n",
    "stdin, stdout, stderr = ssh.exec_command('sudo apt update')\n",
    "stdin.write('789235\\n')  # 如果需要输入密码\n",
    "stdin.flush()\n",
    "\n",
    "time.sleep(30)  # 等待命令执行完成\n",
    "# 等待命令完成并获取退出状态\n",
    "exit_status = stdout.channel.recv_exit_status()\n",
    "print(f\"命令退出状态: {exit_status}\")  # 0表示成功，非0表示失败\n",
    "\n",
    "ssh.close()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
